<template>
  <div id="addContent" class="main-box">
    <BaseTitle :title="$t('栏目内容编辑')">
      <template #right>
        <BackBtn :back-funtion="prev" />
      </template>
    </BaseTitle>
    <div class="search"></div>
    <el-form ref="form" :model="addForm" :rules="rules" label-position="top" class="flexForm">
      <div class="left">
        <el-form ref="searchForm" :model="searchForm" :rules="searchRules" label-width="top" class="filter-form">
          <el-form-item :label="$t('站点')" prop="site_id">
            <el-select v-model="searchForm.site_id" multiple @change="webChange">
              <el-option v-for="item in webList" :key="item.id" :label="item.domain" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('主栏目')" prop="category_id">
            <el-select v-model="searchForm.category_id" @change="handleChangeColumn" filterable>
              <el-option-group v-for="group in columnList" :key="group.id" :label="group.title">
                <el-option v-for="item in group.category" :key="item.id"
                  :label="item.parent_id != 0 ? `${item.title}` : item.title" :value="+item.id"
                  :disabled="item.disabled" />
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('副栏目')">
            <el-select v-model="searchForm.subColumnId" filterable multiple>
              <el-option-group v-for="group in subColumnList" :key="group.id" :label="group.title">
                <el-option v-for="item in group.category" :key="item.id" :label="item.title" :value="+item.id"
                  :disabled="item.disabled" />
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-form>
        <SubTitle :title="$t('基本信息')" />
        <el-form-item prop="sub_content.title" :label="`${$t('标题')}:`">
          <el-input v-model="addForm.sub_content.title" :placeholder="$t('请输入标题')" />
        </el-form-item>
        <el-form-item prop="sub_content.sub_title" :label="`${$t('副标题')}:`">
          <el-input v-model="addForm.sub_content.sub_title" :placeholder="$t('请输入副标题')" />
        </el-form-item>
        <el-form-item prop="sub_content.description" :label="`${$t('简介')}:`">
          <el-input v-model="addForm.sub_content.description" :placeholder="$t('请输入简介')" type="textarea"
            :autosize="{ minRows: 4 }" />
        </el-form-item>
        <el-form-item :label="`${$t('内容')}:`">
          <div>
            <MyTinymce ref="myTinymce" :tinymce-html="tinymceContent" :article-id="id" />
          </div>
        </el-form-item>
        <el-form-item :label="`${$t('标签')}:`">
          <el-input v-model="addForm.sub_content.tag" placeholder="标签请用逗号隔开" />
        </el-form-item>

        <div v-if="showFlow" style="width: 100%">
          <h5 class="title">{{ $t('进度') }}</h5>
          <el-steps direction="vertical" :active="activeFlow">
            <el-step v-for="(item, index) in check_step_list" :key="index" :title="item.name">
              <div slot="description">
                <div class="progress">
                  <div class="text">
                    <p>{{ item.content }}</p>
                  </div>
                  <div v-if="item.status === 4" class="btn">
                    <el-button type="text" @click="handleRejectReason(item.reason)">
                      {{ $t('驳回原因') }}
                    </el-button>
                    <el-button v-if="item.file_list && item.file_list.length" type="text"
                      @click="handleRejectFile(item.file_list)">
                      {{ $t('驳回附件') }}
                    </el-button>
                  </div>
                </div>
              </div>
            </el-step>
          </el-steps>
        </div>
      </div>
      <div class="right">
        <SubTitle :title="$t('SEO设置')" />
        <el-form-item prop="seo_title" label="Title:">
          <el-input v-model="addForm.sub_content.seo_title" :placeholder="$t('请输入seo标题')" />
        </el-form-item>
        <el-form-item prop="seo_keyword" label="Keyword:">
          <el-input v-model="addForm.sub_content.seo_keyword" :placeholder="$t('请输入seo关键词')" />
        </el-form-item>
        <el-form-item prop="seo_description" label="Description:">
          <el-input v-model="addForm.sub_content.seo_description" type="textarea" :placeholder="$t('请输入seo描述')"
            :autosize="{ minRows: 4 }" />
        </el-form-item>
        <SubTitle :title="$t('其他信息')" />
        <el-form-item prop="author" :label="`${$t('作者')}:`">
          <el-input v-model="addForm.sub_content.author" :placeholder="$t('请输入作者名称')" />
        </el-form-item>
        <el-form-item :label="`${$t('模板')}:`">
          <el-select v-model="addForm.sub_content.detail_tpl">
            <el-option v-for="item in themeList" :key="item.id" :label="item.file" :value="item.file" />
          </el-select>
        </el-form-item>
        <el-form-item prop="url" :label="`${$t('跳转链接')}:`">
          <el-input v-model="addForm.sub_content.url" :placeholder="$t('请输入跳转链接')" />
        </el-form-item>
        <el-form-item :label="`${$t('发布时间')}:`" prop="publish_time">
          <el-date-picker v-model="addForm.sub_content.publish_time" type="datetime" :placeholder="$t('请选择发布时间')"
            value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item prop="hits" :label="`${$t('浏览量')}:`">
          <el-input v-model="addForm.sub_content.hits" :placeholder="$t('请输入浏览量')" />
        </el-form-item>
        <el-form-item prop="sort" :label="`${$t('排序')}:`">
          <el-input v-model="addForm.sub_content.sort" :placeholder="$t('请输入排序')" />
        </el-form-item>
        <el-form-item v-if="addForm.sub_content.new_status == 1" prop="status" :label="`${$t('状态')}:`">
          <el-switch v-model="addForm.sub_content.status" :active-text="$t('正常')" :inactive-text="$t('禁用')"
            :active-value="1" :inactive-value="2" active-color="var(--huocms-com-color-primary)"
            inactive-color="rgba(0,0,0,0.2)" />
        </el-form-item>
        <el-form-item prop="is_top" :label="`${$t('是否置顶')}:`">
          <el-switch v-model="addForm.sub_content.is_top" :active-text="$t('置顶')" :inactive-text="$t('否')"
            :active-value="1" :inactive-value="2" active-color="var(--huocms-com-color-primary)"
            inactive-color="rgba(0,0,0,0.2)" />
        </el-form-item>
        <el-form-item prop="is_recommend" :label="`${$t('是否推荐')}:`">
          <el-switch v-model="addForm.sub_content.is_recommend" :active-text="$t('推荐')" :inactive-text="$t('否')"
            :active-value="1" :inactive-value="2" active-color="var(--huocms-com-color-primary)"
            inactive-color="rgba(0,0,0,0.2)" />
        </el-form-item>
        <el-form-item size="small" :label="`${$t('缩略图')}:`">
          <div class="attachment_imgBox" @click="openList('thumbnail')">
            <img v-if="addForm.sub_content.thumbnail" :src="thumbnailImg" class="attachmentImg" />
            <i v-else class="el-icon-camera" />
            <span v-if="addForm.sub_content.thumbnail" class="img-actions attachmentImg">
              <span @click.stop="handleRemove(1)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
          <Attachment ref="attachment" :dialog-show.sync="dialogShow" :attachment-type="attachmentType" @func="getData" />
        </el-form-item>
        <el-form-item :label="`${$t('详情页banner')}:`">
          <div class="attachment_imgBox" @click="openList('cover')">
            <img v-if="addForm.sub_content.cover" :src="coverImg" class="attachmentImg" />
            <i v-else class="el-icon-camera" />
            <span v-if="addForm.sub_content.cover" class="img-actions attachmentImg">
              <span @click.stop="handleRemove(2)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <div style="width: 100%">
      <SubTitle :title="$t('附加信息')" />
      <PublicForm ref="publicForm" :form-obj="formObj" :form-data="formData" :second-data="secondData"
        :rules="mainRules" />
    </div>
    <br />
    <div class="flexCenter">
      <el-button v-if="$route.query.type == 'copy'" type="primary" @click="onSubmit(3)" class="tianBlue"
        style="width: 100px">
        {{ $t('暂存') }}
      </el-button>
      <el-button :loading="loading" style="width: 100px" type="primary" v-if="$route.query.type !== 'examine'"
        @click="onSubmit(1, $route.query.type)">
        {{
          id && $route.query.type != 'copy'
          ? this.$t('立即修改')
          : this.$t('添加')
        }}
      </el-button>
      <template v-if="$route.query.type === 'examine'">
        <el-button style="width: 100px" @click="handleExamine(false)">
          {{ $t('拒绝') }}
        </el-button>
        <el-button style="width: 100px" type="primary" @click="handleExamine(true)">
          {{ $t('通过') }}
        </el-button>
      </template>
    </div>
    <ApprovalReject :file-list="rejectFileList" :dialog-show.sync="rejectFileShow" />
    <BaseDialog width="550px" :title="$t('审核')" :dialog-show.sync="rejectDialogShow" :footer="true"
      @submit="handleSubmitReject" @cancel="handleClose">
      <el-form label-position="top">
        <el-form-item :label="`${$t('拒绝原因')}:`">
          <el-input v-model="rejectForm.reason" type="textarea" :placeholder="$t('请输入拒绝原因')" />
        </el-form-item>
        <el-form-item :label="`${$t('拒绝附件')}:`">
          <BaseUpload v-model="rejectForm.file" description=" " />
        </el-form-item>
      </el-form>
    </BaseDialog>
  </div>
</template>

<script>
import columnApi from '@/api/column'
import moduleApi from '@/api/module'
import tempApi from '@/api/theme'

import PublicForm from './components/updateForms.vue'
import webApi from '@/api/website'
import ApprovalReject from './components/approvalReject.vue'

export default {
  name: 'AddArticle',
  components: { ApprovalReject, PublicForm },
  //   mixins: [mixin],

  data() {
    return {
      rejectForm: {},
      rejectDialogShow: false,
      rejectFileList: [],
      rejectFileShow: false,
      attachmentType: '',
      themeList: [],
      attachmentLimit: 10,
      webList: [],
      type: '',
      dialogShow: false,
      attachmentData: [],
      tinymceContent: '',
      secondData: {},
      formObj: [],
      formData: {},
      mainRules: [],
      searchForm: {
        lang: '',
        modle_id: '',
        category_id: '',
        site_id: []
      },
      moduleList: [],
      columnList: [],
      subColumnList: [], // 副栏目数据
      currentModuleId: '', // 当前选择模型id
      formTypeSource: {}, // 自定义字段数据源
      check_step_list: [],
      website_id: '',
      myHeaders: { Authorization: `Bearer ${this.$store.getters.token}` },
      headers: {},
      imageUrl: '',
      imgUrl: this.$store.getters.updateURL,
      checkList: [],
      tindata: '',
      ticShow: false,
      options: [],
      value: '',
      pageLoading: false, // 页面加载
      id: '',
      category_id: '',
      module_id: '',
      loading: false,
      searchRules: {
        // model_id: [
        //   { required: true, message: '请选择模型', trigger: 'change' }
        // ],
        site_id: [
          { required: true, message: this.$t('请选择站点'), trigger: 'change' }
        ],
        category_id: [
          { required: true, message: this.$t('请选择栏目'), trigger: 'change' }
        ]
      },
      form: {
        label: '',
        title: '',
        cate_id: '',
        push_time: '',
        image_url: '',
        content: '',
        source: '词爪官方',
        is_hot: 2
        // content1: '', // 富文本原文
        // content2: '' // 富文本html
      },
      rules: {
        sub_content: {
          title: [
            {
              required: true,
              message: this.$t('请选择文章标题'),
              trigger: 'blur'
            }
          ]
        },
        main_content: {
          title: [
            {
              required: true,
              message: this.$t('请选择文章标题'),
              trigger: 'blur'
            }
          ]
        }
      },
      addForm: {
        module_id: '',
        website_id: '',
        category_id: '',
        // 主表固定字段
        sub_content: {
          tag: '',
          title: '',
          sub_title: '',
          thumbnail: '',
          cover: '',
          hits: '',
          author: '',
          status: '',
          url: '',
          is_top: '',
          is_recommend: '',
          sort: '',
          seo_title: '',
          seo_keyword: '',
          seo_description: '',
          publish_time: '',
          detail_tpl: ''
        },
        // 副表字段
        main_content: {}
      },
      thumbnailImg: '',
      coverImg: '',
      cate_id: '',
      DATA: '',
      lang: '',
      tagData: [],
      website: '',
      dict: {},
      dictmap: [],
      subObj: {},
      siteIds: [],
      categoryIds: [],
      tags: [],
      activeFlow: 0,
      version: 0
    }
  },
  computed: {
    siteId1() {
      return this.$store.getters.siteId
    },
    showFlow() {
      return (
        this.$route.query.type != 'copy' &&
        (this.addForm.sub_content.new_status == 3 ||
          this.addForm.sub_content.new_status == 4)
      )
    }
  },
  watch: {
    siteId1(val, value) {
      this.website_id = val
      this.getInfo()
      this.getTemp()

      if (value) {
        this.$router.push({ name: 'Content' })
      }
    }
  },
  created() {
    this.website_id = this.$store.getters.siteId
    this.id = this.$route.query.id
    this.lang = this.$route.query.lang
    this.currentModuleId = this.$route.query.module_id
    if (this.website_id) {
      this.getTemp()
      this.getInfo()
    }
  },

  methods: {
    // 移除图片数据
    handleRemove(type) {
      if (type == 1) {
        // 移除缩略图
        this.addForm.sub_content.thumbnail = ''
        this.thumbnailImg = ''
      } else {
        // 移除banner图
        this.addForm.sub_content.cover = ''
        this.coverImg = ''
      }
    },
    async handleExamine(type) {
      const check_data = [
        {
          version: this.version,
          id: this.$route.query.id
        }
      ]
      if (type) {
        const res = await this.$confirm(
          this.$t('此操作将通过审核'),
          this.$t('提示'),
          {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消')
          }
        ).catch(err => console.log(err))
        if (res) {
          this.checkData({
            status: 3,
            check_data
          })
        }
      } else {
        this.rejectDialogShow = true
      }
    },
    // 审批数据
    async checkData(data) {
      const result = await columnApi.checkContent(data)
      if (result.code == 0) {
        this.$message.success(result.msg)
        this.rejectForm = {}
        this.rejectForm.file = []
        this.rejectDialogShow = false
        this.$router.back()
      } else {
        this.$message.error(result.msg)
      }
    },
    handleSubmitReject() {
      if (!this.rejectForm.file?.length || !this.rejectForm.reason) {
        this.$message.error(this.$t('请填写信息'))
        return
      }
      const res = {
        status: 4,
        reason: this.rejectForm.reason,
        files: this.rejectForm.file.map(item => item.id),
        check_data: [
          {
            version: this.version,
            id: this.$route.query.id
          }
        ]
      }
      this.checkData(res)
    },
    handleClose() {
      this.rejectForm = {}
      this.rejectForm.file = []
    },
    // 查看驳回原因
    handleRejectReason(reason) {
      this.$alert(reason || this.$t('暂无信息'), this.$t('驳回原因'))
    },
    handleChangeColumn(e) {
      this.getSubColumnList(e)
      this.searchForm.subColumnId = []
    },
    // 获取主栏目列表
    async getColumnList() {
      if (this.searchForm.site_id.length) {
        const res = await moduleApi.getModuleCate({
          lang: this.lang,
          site_id: this.searchForm.site_id
        })
        this.columnList = res.data
        this.getSubColumnList(this.searchForm.category_id)
      } else {
        this.columnList = []
      }
    },
    // 获取副栏目数据
    getSubColumnList(e) {
      const newData = []
      this.columnList.find(item => {
        const result = item.category.find(child => child.id == e)
        if (result?.module_id) {
          this.currentModuleId = result.module_id
        }
      })
      this.columnList.forEach(item => {
        newData.push({
          ...item,
          category: item.category.filter(
            ele => ele.module_id === +this.currentModuleId && ele.id !== e
          )
        })
      })
      this.subColumnList = newData
      this.getSubform()
    },
    getData(data) {
      if (data.length > 1) {
        this.$message.error(this.$t('最多只能选择一张图片'))
      } else {
        if (this.type == 'thumbnail') {
          this.addForm.sub_content.thumbnail = data[0].id
          this.thumbnailImg = data[0].url
        } else if (this.type == 'cover') {
          this.addForm.sub_content.cover = data[0].id
          this.coverImg = data[0].url
        }
        this.dialogShow = false
      }
    },
    // 打开附件弹窗
    openList(val) {
      this.dialogShow = true
      this.attachmentType = 2
      this.$nextTick(() => {
        this.$refs.attachment.getAttachmentList()
        this.$refs.attachment.$refs.AttachmentCate.getCateList(0)
      })
      this.type = val
    },
    getTemp() {
      tempApi
        .webTempList({ website_id: this.website_id, lang: this.lang })
        .then(res => {
          this.themeList = res.data
        })
    },
    // 获取主副表数据
    getInfo() {
      const val = {
        id: this.id,
        module_id: this.$route.query.module_id,
        website_id: this.website_id,
        lang: this.lang
      }

      columnApi.contentInfo(val).then(async res => {
        this.siteIds = res.data.content.website
        await this.getWebList()
        this.searchForm.site_id = [+this.siteIds]
        await this.getColumnList()
        this.categoryIds = res.data.content.category
        this.DATA = res.data.content.main_content
        this.searchForm.website_id = res.data.content.website
        this.searchForm = {
          ...this.searchForm,
          category_id: res.data.content.category_id,
          subColumnId: res.data.content.sub_category_ids
            ? res.data.content.sub_category_ids.split(',').map(item => +item)
            : []
        }
        this.check_step_list = res.data.content.check_step_list
        this.activeFlow = res.data.content.check_step_list.length - 1
        this.version = res.data.content.version
        // 主表内容
        this.addForm.sub_content = {
          title: res.data.content.title,
          sub_title: res.data.content.sub_title,
          detail_tpl: res.data.content.detail_tpl,
          description: res.data.content.description,
          tag: res.data.content.tag,
          content: this.setTin(res.data.content.content),
          author: res.data.content.author,
          hits: res.data.content.hits,
          sort: res.data.content.sort,
          url: res.data.content.url,
          status: res.data.content.status,
          publish_time: res.data.content.publish_time,
          is_top: res.data.content.is_top,
          is_recommend: res.data.content.is_recommend,
          seo_title: res.data.content.seo_title,
          seo_keyword: res.data.content.seo_keyword,
          seo_description: res.data.content.seo_description,
          cover: res.data.content.cover ? res.data.content.cover.id : '',
          new_status: res.data.content.new_status,
          thumbnail: res.data.content.thumbnail
            ? res.data.content.thumbnail.id
            : ''
        }

        this.coverImg =
          res.data.content.cover != null ? res.data.content.cover.url : ' '
        this.thumbnailImg =
          res.data.content.thumbnail != null
            ? res.data.content.thumbnail.url
            : ' '
        const obj = res.data.field

        const arr = []
        for (const i in obj) {
          arr.push(obj[i])
        }
        this.formObj = arr
        arr.forEach(el => {
          if (
            el.form_type == 'image' &&
            res.data.content.main_content[el.table_field]
          ) {
            this.$set(
              this.formData,
              el.table_field,
              res.data.content.main_content[el.table_field].id
            )
            this.$set(
              this.secondData,
              el.table_field,
              res.data.content.main_content[el.table_field].id
            )
          } else if (
            el.form_type == 'file' &&
            res.data.content.main_content[el.table_field]
          ) {
            this.$set(
              this.formData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
            this.$set(
              this.secondData,
              el.table_field,
              res.data.content.main_content[el.table_field].id
            )
          } else if (
            el.form_type == 'video' &&
            res.data.content.main_content[el.table_field]
          ) {
            this.$set(
              this.formData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
            this.$set(
              this.secondData,
              el.table_field,
              res.data.content.main_content[el.table_field].id
            )
          } else if (el.form_type == 'richText') {
            this.$refs.publicForm.setTin(
              res.data.content.main_content[el.table_field]
            )
            // this.formData[el.table_field] = res.data.content.main_content[el.table_field]
            this.$set(
              this.formData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
            this.$set(
              this.secondData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
          } else if (
            el.form_type == 'multiImage' &&
            res.data.content.main_content[el.table_field]
          ) {
            this.$set(
              this.formData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
            const a = res.data.content.main_content[el.table_field]
            const b = []
            a.forEach(item => {
              b.push(item.id)
            })
            this.$set(this.secondData, el.table_field, b)
          } else if (
            el.form_type == 'multiVideo' &&
            res.data.content.main_content[el.table_field]
          ) {
            this.$set(
              this.formData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
            const a = res.data.content.main_content[el.table_field]
            const b = []
            a.forEach(item => {
              b.push(item.id)
            })
            this.$set(this.secondData, el.table_field, b)
          } else if (
            el.form_type == 'multiFile' &&
            res.data.content.main_content[el.table_field]
          ) {
            this.$set(
              this.formData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
            const a = res.data.content.main_content[el.table_field]
            const b = []
            a.forEach(item => {
              b.push(item.id)
            })
            this.$set(this.secondData, el.table_field, b)
          } else if (el.form_type == 'reference') {
            const arr3 = res.data.content.main_content[el.table_field]
            const arr4 = []
            if (arr3.length) {
              arr3.forEach(item => {
                arr4.push(item[el.settings.foreign_key])
                this.$set(this.formData, el.table_field, arr4)
                this.$set(this.secondData, el.table_field, arr4)
              })
            } else {
              this.$set(
                this.formData,
                el.table_field,
                arr3[el.settings.foreign_key]
              )
              this.$set(
                this.secondData,
                el.table_field,
                arr3[el.settings.foreign_key]
              )
            }
          } else {
            this.$set(
              this.formData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
            this.$set(
              this.secondData,
              el.table_field,
              res.data.content.main_content[el.table_field]
            )
          }
        })
        // this.formData = this.formData
      })
    },
    handleRejectFile(row) {
      this.rejectFileList = row
      this.rejectFileShow = true
    },
    // 获取主副表的字段
    getSubform(formData) {
      this.addForm.module_id = this.searchForm.modle_id
      this.addForm.category_id = this.searchForm.category_id
      this.addForm.website_id = this.website_id
      moduleApi.fieldList({ module_id: this.currentModuleId }).then(res => {
        if (res.code == 0) {
          //
          this.formObj = []
          const arr = Object.values(res.data)
          arr.forEach(el => {
            let arr2 = []
            var option = []
            if (el.validate_rule == 'date' || el.validate_rule == 'time') {
              const rules = [
                {
                  required: true,
                  message: this.$t('请选择日期或时间'),
                  trigger: 'blur'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                const rule = []
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              }
            } else if (el.validate_rule == 'email') {
              const rules = [
                {
                  required: true,
                  message: this.$t('请输入邮箱'),
                  trigger: 'blur'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                const rule = []
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              }
            } else if (el.form_type == 'image' || el.form_type == 'file') {
              const rules = [
                {
                  required: true,
                  message: this.$t('请上传图片'),
                  trigger: 'change'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                // const rule = []
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  list: [],
                  id: this.DATA[el.table_field] ? el.id : '',
                  type: el.form_type,
                  IMGURL: this.DATA[el.table_field]
                    ? this.DATA[el.table_field].url
                    : ''
                })
              }
            } else if (el.form_type == 'multiImage') {
              const rules = [
                {
                  required: true,
                  message: this.$t('请上传图片'),
                  trigger: 'change'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  list: this.DATA[el.table_field],
                  id: this.DATA[el.table_field] ? el.id : '',
                  type: el.form_type
                  // IMGURL: this.DATA[el.table_field] ? this.DATA[el.table_field].url : ''
                })
              }
            } else if (el.form_type == 'multiVideo') {
              const rules = [
                {
                  required: true,
                  message: this.$t('请选择视频'),
                  trigger: 'change'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  list: this.DATA[el.table_field],
                  id: this.DATA[el.table_field] ? el.id : '',
                  type: el.form_type
                  // IMGURL: this.DATA[el.table_field] ? this.DATA[el.table_field].url : ''
                })
              }
            } else if (el.form_type == 'multiFile') {
              const rules = [
                {
                  required: true,
                  message: this.$t('请选择文件'),
                  trigger: 'change'
                }
              ]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  list: this.DATA[el.table_field],
                  id: this.DATA[el.table_field] ? el.id : '',
                  type: el.form_type
                  // IMGURL: this.DATA[el.table_field] ? this.DATA[el.table_field].url : ''
                })
              }
            } else if (el.form_type == 'reference') {
              if (el.settings.relation == 'has_one') {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == '' ? [] : el.validate_rule,
                  options: el.attach_data,
                  list: [],
                  id: el.id,
                  multiple: false, // 单选
                  relation_file: el.settings.foreign_key
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == '' ? [] : el.validate_rule,
                  options: el.attach_data,
                  list: [],
                  id: el.id,
                  multiple: true, // 多选
                  relation_file: el.settings.foreign_key
                })
              }
            } else {
              const rules = [{ required: true, message: '' }]
              if (el.attach_data) {
                arr2 = el.attach_data.split(',')
                arr2.forEach((el, idx) => {
                  option.push({
                    label: el,
                    value: idx
                  })
                })
                const rule = []
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  options: el.attach_data ? option : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              } else {
                this.formObj.push({
                  [el.form_type]: true,
                  label: el.form_title,
                  prop: el.table_field,
                  rules: el.validate_rule == 'require' ? rules : [],
                  list: [],
                  id: el.id,
                  type: el.form_type
                })
              }
            }
          })
        }
      })
    },
    // 站点列表
    async getWebList() {
      const res = await webApi.websiteList()
      this.getTreeData(res.data)
    },
    // 递归获取到站点的数据
    getTreeData(data) {
      const webListArray = []
      function transformWebList(data) {
        if (data.length) {
          data.forEach(item => {
            webListArray.push({
              id: item.id,
              domain: item.parent_id != 0 ? `--${item.domain}` : item.domain,
              parent_id: item.parent_id
            })
            if (item.children.length) {
              transformWebList(item.children)
            }
          })
        }
      }
      transformWebList(data)
      this.webList = webListArray
    },
    webChange(val) {
      this.searchForm.site_id = val
      this.searchForm.category_id = []
      this.searchForm.subColumnId = []
      this.getColumnList()
    },
    // 提交按钮
    onSubmit(status = 1, type) {
      this.addForm.sub_content.content = this.getTin()
      // 判断rules
      // 判断副表有无富文本
      const newArr = this.$refs.publicForm.$refs.myTinymce
      if (newArr) {
        newArr.forEach(item => {
          this.secondData[item.prop] = item.codeValue
        })
      }
      this.$refs.form.validate(async valid => {
        if (valid) {
          const val = {
            module_id: this.currentModuleId,
            category_id: [
              this.searchForm.category_id,
              ...this.searchForm.subColumnId
            ],
            sub_content: {
              ...this.addForm.sub_content,
              category_id: this.searchForm.category_id,
              sub_category_ids: this.searchForm.subColumnId.join(','),
              status
            },
            id: this.id
          }
          if (JSON.stringify(this.formData) == '{}') {
            val.main_content = {
              id: this.DATA.id,
              lang: this.DATA.lang,
              lang_pid: this.DATA.lang_pid,
              sub_id: this.DATA.sub_id
            }
          } else {
            val.main_content = this.secondData
          }
          // return
          this.loading = true
          // 把空数组转为空字符串 避免Qs.stringify识别不了空数组
          for (const item in val.main_content) {
            if (Array.isArray(val.main_content[item])) {
              console.log(val.main_content[item]?.length)
              if (val.main_content[item]?.length == 0) {
                val.main_content[item] = ''
              }
            }
          }
          // return
          let res = null
          if (status == 3 || type === 'copy') {
            res = await columnApi.contentSave(val)
          } else {
            res = await columnApi.contentUpdate(val)
          }
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.prev()
          }
          this.loading = false
        } else {
          this.$message.warning(this.$t('请填写必要信息'))
        }
        // })
      })
    },

    // 获取富文本框内容
    getTin() {
      var rs = this.$refs.myTinymce.codeValue
      return rs
    },
    // 设置富文本框内容
    setTin(v) {
      // this.$refs.myTinymce.value = v
    },
    // 返回上一页
    prev() {
      this.$router.push({
        name: 'Content',
        query: { category_id: this.searchForm.category_id, lang: this.lang }
      })
      // this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss">
#addContent {

  .el-select,
  .el-input,
  .el-textarea,
  .el-date-editor {
    width: 100%;
  }
}

.attachment .el-dialog {
  height: 640px;
}
</style>
<style scoped lang="scss">
.filter-form {
  .el-form-item {
    margin-bottom: 24px;
  }
}

.progress {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .text {
    display: flex;

    p {
      margin-right: 20px;
    }
  }

  .el-button {
    padding: 0;
  }
}

.flexCenter {
  margin-bottom: 16px;
}

@media screen and (max-width: 1380px) {
  .el-card {
    min-width: 980px;
  }

  .form {
    display: block;
  }

  .left {
    width: 100%;
  }

  .right {
    width: 100%;
  }

  .back {
    top: 24px;
  }
}

.attachment_imgBox .img-actions {
  position: absolute;
  background: rgba($color: #000000, $alpha: 0.3);
  top: 1px;
  left: 3px;
  transition: all 0.5s;
  -moz-transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -o-transition: all 0.5s;
  opacity: 0;
}

.attachment_imgBox .img-actions>span {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

.attachment_imgBox .img-actions>span>i {
  color: #f00;
  font-size: 22px;
}

.attachment_imgBox:hover .img-actions {
  opacity: 1;
}
</style>
